package com.iiapk.gridnew.view;

import java.io.ByteArrayOutputStream;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.support.v1.util.LocalCacheManager;
import android.util.AttributeSet;
import android.widget.ImageView;

public class RemoteImageView extends ImageView {
	
	public ObjectHolder objectHolder;
	
	public RemoteImageView(Context context, AttributeSet attrs) {
		super(context, attrs);
	}

	public void loadImage(String url) {
		objectHolder=new ObjectHolder(url);
		new LoadImageTask().execute();
	}

	public class ObjectHolder{
		public ObjectHolder(String url) {
			super();
			this.url = url;
			this.local=url;
		}
		public String url;
		public String local;
	}
	
	class LoadImageTask extends AsyncTask<Integer, Void, Bitmap> {
		
		LocalCacheManager localCacheManager;
		Bitmap bitmap;
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			localCacheManager = LocalCacheManager.getInstance(); 
		}
		
		@Override
		protected Bitmap doInBackground(Integer... params) {
			//bitmap = localCacheManager.loadFileFromDiskCache(objectHolder.local,objectHolder.url);
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}
		
		protected void onPostExecute(Bitmap result) {
			super.onPostExecute(result);
			setFromLocal(bitmap);
		}
		
		private void setFromLocal(Bitmap bitmap) {
			if (bitmap != null) {
				ByteArrayOutputStream stream = new ByteArrayOutputStream(); 
				bitmap.compress(Bitmap.CompressFormat.JPEG,0,stream);   
				setImageBitmap(bitmap);
			}else{
				setImageResource(Integer.parseInt(objectHolder.local));
			}
		}
		
	}
	
}